package com.aaa.member.service.impl;

import com.aaa.entity.MbsLoginLog;
import com.aaa.member.dao.MemberLoginDao;
import com.aaa.member.service.MemberLoginService;
import com.aaa.member.util.UserAgentUtils;
import com.aaa.util.JwtUtil;
import com.aaa.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author 崔灿
 * @Date 2023/03/03 10:47
 * @ClassName MemberLoginServiceImpl
 * @Description
 * @Version 1.0
 */

@Service
public class MemberLoginServiceImpl implements MemberLoginService {
    @Autowired
    private MemberLoginDao memberLoginDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Result login(HttpServletRequest request ,String username, String password) {
        String userAgent = request.getHeader("user-agent");
        String selectpassword = memberLoginDao.selectpassword(username);
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        if (passwordEncoder.matches(password,selectpassword)){
            Map<String,Object> map=new HashMap<>();
            map.put("username",username);
            String token = JwtUtil.createJWT(map);
            //存入redis中。
            redisTemplate.opsForValue().set(token,"",30, TimeUnit.MINUTES);
            MbsLoginLog mbsLoginLog = new MbsLoginLog();
            mbsLoginLog.setMemberName(username);
            mbsLoginLog.setIpaddress(UserAgentUtils.getIpAddress(request));
            mbsLoginLog.setBrowser(UserAgentUtils.getBorderName(userAgent));
            mbsLoginLog.setOs(UserAgentUtils.getOsName(userAgent));
            mbsLoginLog.setMsg("会员登录成功");
            mbsLoginLog.setStatus(0);
            mbsLoginLog.setLoginTime(new Date());
            memberLoginDao.insert(mbsLoginLog);
            return new Result(2000,"登录成功",token);
        }
        return new Result(5000,"登录失败");
    }
}
